<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>5_列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!-- 准备一个容器 -->
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="搜索内容" v-model="keyword">
        <button @click="sortType = 1">年龄升序</button>
        <button @click="sortType = 2">年龄降序</button>
        <button @click="sortType = 0">原先顺序</button>
        <ul>
            <h3>查询结果</h3>
            <li v-for="(p,idx) in filPersons" :key="p.id">
                {{p.id}}-{{p.name}}-{{p.age}}
            </li>
        </ul>
    </div>

    <script type="text/javascript">
        new Vue({
            el:'#root',
            data(){
                return{
                    sortType:0,//1升序，2降序
                    keyword:'',
                    persons:[
                        {
                            id:'001',
                            name:'马冬梅',
                            age:19
                        },
                        {
                            id:'002',
                            name:'周冬雨',
                            age:2
                        },
                        {
                            id:'003',
                            name:'周杰伦',
                            age:45
                        },
                        {
                            id:'004',
                            name:'温兆伦',
                            age:59
                        },
                    ]
                }
            },
            
            // computed实现
            computed:{
                filPersons(){
                    let arr = this.persons.filter(p => {
                        return p.name.indexOf(this.keyword) !== -1
                    })
                    // 判断是否需要排序
                    if(this.sortType) {
                        arr.sort((a,b) => {
                            return this.sortType === 1 ? a.age-b.age : b.age-a.age
                        })
                    }
                    return arr
                }
            }
            
        })
    </script>
</body>

</html>